import './auth.css';

import { useState, useEffect } from 'react';

import LoadingButton from '@mui/lab/LoadingButton';
import InputAdornment from '@mui/material/InputAdornment';
import { Box, Link, TextField, IconButton, Typography } from '@mui/material';

import { useRouter } from 'src/routes/hooks';

import { Iconify } from 'src/components/iconify';

import { login, register } from '../../api/user-api';
import { MessageBox } from '../../components/Snackbar/message-box';

export function SignInView() {
  const router = useRouter();

  const [showPassword, setShowPassword] = useState(false);
  const [password, setPassword] = useState('');
  const [account, setAccount] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [isCheckingAuth, setIsCheckingAuth] = useState(true);
  const [isFlipped, setIsFlipped] = useState(false); // 用于控制翻转状态

  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('success');

  const [showMessage, setShowMessage] = useState(false);
  const [message, setMessage] = useState('');

  const isAuthenticated = localStorage.getItem('isAuthenticated');

  useEffect(() => {
    if (isAuthenticated === 'true') {
      router.push('/');
    } else {
      setIsCheckingAuth(false); // 如果未认证，继续渲染登录页面
    }
  }, [isAuthenticated, router]);

  const onClose = () => {
    setShowMessage(false);
  };
  const handleRegister = async () => {
    if (!account || !password) {
      setError('Please enter both account and password!');
      return;
    }
    setError('');
    setLoading(true);

    try {
      const params = { account, password };
      const result = await register(params);
      if (result.code === 200) {
        setMessage('注册成功，请登录');
        setSeverity('success');
        setShowMessage(true);
        // 注册成功后，清空表单并切换到登录页面
        setTimeout(() => {
          setAccount('');
          setPassword('');
          setError('');
          setIsFlipped(false);
          setShowMessage(false);
        }, 2000);
      } else {
        setShowMessage(true);
        setMessage(result.data);
        setSeverity('error');
      }
    } catch (e) {
      console.error('Registration failed', e);
      setShowMessage(true);
      setMessage('注册失败，请重试');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };
  const handleSignIn = async () => {
    if (!account || !password) {
      setError('Please enter both account and password!');
      return;
    }
    setError('');
    setLoading(true);
    try {
      const params = { account, password };
      const result = await login(params);
      if (result.code === 200) {
        localStorage.setItem('isAuthenticated', 'true');
        localStorage.setItem('token', result.data);
        router.push('/');
      } else {
        setError(result.data);
      }
    } catch (e) {
      console.error('Sign-in failed', e);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSignIn();
    }
  };

  const handleGetStartedClick = () => {
    setIsFlipped(true); // 点击 Get started 时翻转
  };

  const handleBackToLogin = () => {
    setIsFlipped(false); // 点击返回登录时翻转回登录界面
  };

  if (isCheckingAuth) {
    return null; // 正在检查认证状态时，不显示页面内容
  }

  return (
    <>
      <Box display="flex" justifyContent="center" alignItems="center" height="60vh">
        <div className={`auth-container ${isFlipped ? 'flipped' : ''}`}>
          <div className="auth-box">
            {/* 登录表单 */}
            {!isFlipped && (
              <div className="auth-form">
                <Box
                  gap={1.5}
                  display="flex"
                  flexDirection="column"
                  alignItems="center"
                  sx={{ mb: 5 }}
                >
                  <Typography variant="h5">登陆</Typography>
                  <Typography variant="body2" color="text.secondary">
                    还没有账号?
                    <Link variant="subtitle2" sx={{ ml: 0.5 }} onClick={handleGetStartedClick}>
                      立即注册
                    </Link>
                  </Typography>
                </Box>

                <Box display="flex" flexDirection="column" alignItems="flex-end">
                  <TextField
                    fullWidth
                    name="account"
                    value={account}
                    label="账户"
                    onChange={(e) => setAccount(e.target.value)}
                    InputLabelProps={{ shrink: true }}
                    sx={{ mb: 3 }}
                    error={!!error}
                    onKeyDown={handleKeyDown}
                  />

                  <Link
                    variant="body2"
                    color="inherit"
                    sx={{ mb: 1.5 }}
                    onClick={() => router.push('/up-passwd')}
                  >
                    忘记密码?
                  </Link>

                  <TextField
                    fullWidth
                    name="password"
                    label="密码"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    InputLabelProps={{ shrink: true }}
                    type={showPassword ? 'text' : 'password'}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton onClick={() => setShowPassword(!showPassword)} edge="end">
                            <Iconify
                              icon={showPassword ? 'solar:eye-bold' : 'solar:eye-closed-bold'}
                            />
                          </IconButton>
                        </InputAdornment>
                      ),
                    }}
                    sx={{ mb: 3 }}
                    error={!!error}
                    onKeyDown={handleKeyDown}
                  />

                  {error && (
                    <Typography variant="body2" color="error" sx={{ mb: 2 }}>
                      {error}
                    </Typography>
                  )}

                  <LoadingButton
                    fullWidth
                    size="large"
                    type="button"
                    color="inherit"
                    variant="contained"
                    onClick={handleSignIn}
                    loading={loading}
                  >
                    Sign in
                  </LoadingButton>
                </Box>
              </div>
            )}

            {/* 注册表单 */}
            {isFlipped && (
              <div className="auth-form auth-form-back">
                <Box
                  gap={1.5}
                  display="flex"
                  flexDirection="column"
                  alignItems="center"
                  sx={{ mb: 5 }}
                >
                  <Typography variant="h5">注册</Typography>
                  <Typography variant="body2" color="text.secondary">
                    已经有帐号?
                    <Link variant="subtitle2" sx={{ ml: 0.5 }} onClick={handleBackToLogin}>
                      返回登陆
                    </Link>
                  </Typography>
                  <Box sx={{ height: '30px' }} />

                  <Box display="flex" flexDirection="column" alignItems="flex-end" width="100%">
                    <TextField
                      fullWidth
                      name="account"
                      value={account}
                      label="账户"
                      onChange={(e) => setAccount(e.target.value)}
                      InputLabelProps={{ shrink: true }}
                      sx={{ mb: 3 }}
                      error={!!error}
                      onKeyDown={handleKeyDown}
                    />
                    <Box sx={{ height: '30px' }} />
                    <TextField
                      fullWidth
                      name="password"
                      label="密码"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      InputLabelProps={{ shrink: true }}
                      type={showPassword ? 'text' : 'password'}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton onClick={() => setShowPassword(!showPassword)} edge="end">
                              <Iconify
                                icon={showPassword ? 'solar:eye-bold' : 'solar:eye-closed-bold'}
                              />
                            </IconButton>
                          </InputAdornment>
                        ),
                      }}
                      sx={{ mb: 3 }}
                      error={!!error}
                      onKeyDown={handleKeyDown}
                    />

                    {error && (
                      <Typography variant="body2" color="error" sx={{ mb: 2 }}>
                        {error}
                      </Typography>
                    )}

                    <LoadingButton
                      fullWidth
                      size="large"
                      type="button"
                      color="inherit"
                      variant="contained"
                      onClick={handleRegister}
                      loading={loading}
                    >
                      Sign in
                    </LoadingButton>
                  </Box>
                </Box>
              </div>
            )}
          </div>
        </div>
      </Box>
      <MessageBox
        message={message}
        showMessage={showMessage}
        onClose={onClose}
        severity={severity}
      />
    </>
  );
}
